package userShareModuleApi

import (
	"KumquatDrivesServices/enums"
	"KumquatDrivesServices/global"
	"KumquatDrivesServices/model"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
	"net/http"
)

type UserShareModuleApi struct{}
type authShareInfo struct {
	ShareId         string                `json:"shareId"`
	ShareUserId     model.SnowflakeIdType `json:"shareUserId"`
	ShareFileId     model.SnowflakeIdType `json:"shareFileId"`
	ShareExpireTime int64                 `json:"shareExpireTime"`
}

func setAuthShareCookie(shareId string, info authShareInfo, c *gin.Context) error {
	infoStr, err := json.Marshal(info)
	if err != nil {
		return err
	}
	http.SetCookie(c.Writer, &http.Cookie{
		Name:     shareId,
		Value:    string(infoStr),
		HttpOnly: true,
	})
	return nil
}
func checkShareAuthState(shareId string, c *gin.Context) (*authShareInfo, error) {
	CookieValue, err := c.Cookie(shareId)
	if err != nil {
		return nil, err
	}
	var info authShareInfo
	if JsonErr := json.Unmarshal([]byte(CookieValue), &info); JsonErr != nil {
		logrus.Errorf("JsonErr: %v value:%s", JsonErr, CookieValue)
		return nil, JsonErr
	}
	if enums.IsExpired(info.ShareExpireTime) {
		return nil, fmt.Errorf("分享过期")
	}
	return &info, nil
}

// isFileWithinSharedFolder 检查该文件是否在用户分享的文件或其子目录中
func isFileWithinSharedFolder(shareFileId, fileId, userId model.SnowflakeIdType) (bool, error) {
	currentFileId := fileId // 当前检查的文件ID
	for {
		// 查询当前文件
		var modelFile model.FileModel
		if err := global.DB.Where("id = ? AND user_id = ? AND del_flag = ?", currentFileId, userId, enums.Normal).First(&modelFile).Error; err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				return false, nil // 文件不存在或已删除
			}
			return false, err
		}

		// 检查是否匹配共享文件ID
		if modelFile.ID == shareFileId {
			return true, nil
		}

		// 检查是否到达根目录（父级ID为1）
		if modelFile.FilePid == 1 {
			break // 已到达根目录且未找到，返回false
		}

		// 继续检查父级文件
		currentFileId = modelFile.FilePid
	}

	return false, nil
}
